<template>
  <div class="app-wrapper">
    <headerTitle
      :titleList="titleList"
      :hideButton="false"
      :btnTitle="'新增视讯号'"
      :btnExport="'批量导入'"
      :exportShow="true"
      @handelClick="() => addOrUpdate()"
      @handelExport="()=> handelExport()"
    />
    <div class="app-container">
      <div class="containerMain">
        <div class="search-item">
          <div class="item-list">
            <div class="item-con">
              <span>视讯号码</span>
              <el-input style="width:200px" size="mini" v-model="searchform.videoNum" placeholder="请输入视讯号码"></el-input>
            </div>
            <div class="item-con">
              <span>号码状态</span>
              <el-select
                size="mini"
                clearable
                v-model="searchform.enable"
                placeholder="全部"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="正常" value="1"></el-option>
                <el-option label="注销" value="2"></el-option>
              </el-select>
            </div>
          </div>
          <div class="item-btn">
            <el-button class="kyeup_search_btn" type="primary" size="mini" @click="() => fetchData()">查询</el-button>
            <el-button type="default" size="mini" @click="() => reset()">重置</el-button>
            <el-button type="danger" size="mini" @click="() => initVideoPool()">初始化视讯号码池</el-button>
          </div>
        </div>
        <div class="container">
          <div class="div-table">
            <el-table
              :header-cell-style="headerStyle"
              :data="list"
              element-loading-text="Loading"
              fit
              size="mini"
              highlight-current-row
            >
              <el-table-column label="号码">
                <template slot-scope="scope">{{ scope.row.videoNum }}</template>
              </el-table-column>
              <el-table-column label="密码">
                <template slot-scope="scope">{{ scope.row.password }}</template>
              </el-table-column>
              <el-table-column label="号码状态">
                <template slot-scope="scope">{{ scope.row.enable | statusFilter }}</template>
              </el-table-column>
              <el-table-column label="操作" width="300px">
                <template slot-scope="scope">
                  <el-button type="text" @click="() => viewFn(scope.row)">查看</el-button>
                  <el-button v-show="scope.row.enable==2" type="text" @click="() => del(scope.row)">删除</el-button>
                  <el-button v-show="scope.row.enable==1" type="text" @click="() => disBtn(scope.row, 2)">禁用</el-button>
                  <el-button v-show="scope.row.enable==2" type="text" @click="() => disBtn(scope.row, 1)">启用</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <pagination :exportShow="true" :type="'primary'" @handelExport="exportDemo(1)" btnExport="导出视讯号" :pagination="pagination" />
    <el-dialog title="批量导入" :visible.sync="dialogVisible" width="500px" :show-close="false">
      <el-form ref="form" label-width="120px">
        <el-form-item label="选择文件">
          <div style="display: flex">
            <el-upload
              class="upload-demo"
              ref="uploadBatch"
              action="string"
              accept=".xlsx, .xls"
              :limit="1"
              :http-request="httpRequestExport"
              :auto-upload="false"
            >
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            </el-upload>
            <div>
              <el-button style="margin-left: 10px" size="small" type="primary" @click="exportDemo(2)">下载模板</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitUpload">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination/index";
import HeaderTitle from "@/components/Headertitle/index";
import selectModule from "@/components/common/selectmodulecopy";
import inputModule from "@/components/common/inputmodule";
import { fetchList, fetchDel, fetchDisabled, initVideoPool, downloadUserInfo, fetchExport } from "@/api/systemapi/videonumber";
import { pageParams } from "@/settings";

export default {
  name: "videonumber",
  components: {
    Pagination,
    HeaderTitle,
    selectModule,
    inputModule
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: "正常",
        2: "注销"
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      entNum:"",
      titleList: [{ title: "视讯号码池管理" }],
      // treeData: null,
      list: null,
      listLoading: true,
      searchform: {
        videoNum: "",
        entNum: "",
        rows: "10",
        page: "1"
      },
      optionOrg: [], // 所属机构
      accountList: [],// 账号权限下拉数组
      organprops: {
        label: 'name',
        children: 'children',
        value: 'id',
        checkStrictly: true
      },
      // 分页
      pagination: pageParams,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      dialogVisible: false,
    };
  },
  watch: {
    // 分页
    "pagination.currentPage": function() {
      this.searchform.page = this.pagination.currentPage;
      this.fetchData();
    },
    "pagination.pageSize": function() {
      this.searchform.rows = this.pagination.pageSize;
      this.searchform.page = 1;
      this.fetchData();
    }
  },
  mounted() {
    const { entNum } = this.$route.params;
    this.entNum = entNum;
    this.searchform.entNum = entNum;
    this.fetchData();

  },
  methods: {
    exportDemo(type){
      downloadUserInfo({...this.searchform,exportType:type}).then(res=>{
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel"
        });
        console.log(res, "res")
        let str = res.headers['content-disposition'].split(';')[1];
        // console.log(str,"str1111")
        if(str.indexOf('=')!=-1){
          var filename = decodeURI(str.slice(9))
        }else {
          var filename = decodeURI(str)
        }
        var downloadElement = document.createElement("a");
        var href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = filename; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      })
    },
    //表头背景颜色修改
    headerStyle({ row, column, rowIndex, columnIndex }) {
      if (rowIndex == 0) {
        return "background:#F5F6FB;color:#666";
      }
    },
    initVideoPool(){
      this.$confirm("是否确定初始化视讯号码池?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          initVideoPool({
          }).then(response => {
            if (response.code === 0) {
              this.fetchData();
              this.$message({
                message: '初始化成功',
                type: "success"
              });
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
    },
    // 重置搜索，刷新列表
    reset() {
      this.searchform = {
        videoNum: "",
        entNum: "",
        rows: "10",
        page: "1"
      },
      this.fetchData();
    },
    fetchData() {
      fetchList({...this.searchform}).then(response => {
        if(response.code==0){
          this.list = response.data.rows;
          this.pagination.total = response.data.records;
        } else {
          this.$message({
            type: 'error',
            message: response.msg
          })
        }
      });
    },
    // 删除
    del(data) {
      this.$confirm("是否确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          fetchDel({
            id: data.id
          }).then(response => {
            if (response.code === 0) {
              this.fetchData();
              this.$message({
                message: '删除成功',
                type: "success"
              });
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
    },
    // 禁用
    disBtn(data, type) {
      this.$confirm(`是否确定${type==2?'禁用':'启用'}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          fetchDisabled({
            id: data.id,
            enable: type
          }).then(response => {
            if (response.code === 0) {
              this.fetchData();
              this.$message({
                message: `${type==2?'禁用':'启用'}成功`,
                type: "success"
              });
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
    },
    // 新增
    addOrUpdate() {
      this.$router.push({ path: "/vpm/videonumber/detail" });
    },
    viewFn(data) {
      this.$router.push({ path: "/vpm/videonumber/detail", query: { type: "2", id: data.id} });
    },
    handelExport() {
      if(this.$refs.uploadBatch){
            this.$refs.uploadBatch.clearFiles()}

      this.dialogVisible = true;

    },
    // 批量导入文件
    httpRequestExport(param) {
      console.log(param, "param")
      let fileObj = param.file; // 相当于input里取得的files
      let fd = new FormData(); // FormData 对象
      fd.append("file", fileObj); // 文件对象
      fetchExport(fd).then(res => {
        if (res.code == 0) {
          this.dialogVisible = false;
          this.fetchData()
        } else {
          this.$message({
            type: "error",
            message: res.msg
          });
        }
      });
    },
    submitUpload() {
      this.$refs.uploadBatch.submit();
    }
    // resetFileds() {
    //   // 重置校验
    //   if (this.$refs["ruleForm"]) {
    //     this.$refs["ruleForm"].resetFields();
    //   }
    // }
  }
};
</script>
<style lang="scss">
.tree-con{
  .el-tree-node__content{
    margin-bottom: 20px;
  }
}
</style>
<style lang="scss" scoped>
.containerMain {
  .search-item {
    padding: 20px 10px;
    font-size: 14px;
    color: #666;
    display: flex;
    justify-content: space-between;
    .item-list{
      display: flex;
      flex-wrap: wrap;
    }
    .item-con {
      display: flex;
      margin-right: 30px;
      span {
        display: inline-block;
        line-height: 28px;
        margin-right: 10px;
      }
    }
    .item {
      width: 180px;
    }
  }
  .container {
    display: flex;
    flex-direction: row;
    .div-tree {
      width: 250px;
    }
    .div-table {
      flex: 1;
      width: 100%;
      overflow: hidden;
      .el-table {
        height: 100%;
        width: 100%;
        overflow: auto;
      }
    }
    .el-row {
      height: 300px;
      .el-col {
        height: 100%;
        .div-tree {
          height: 90%;
          .el-tree {
            height: 100%;
            overflow-y: auto;
          }
        }
      }
    }
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
